import IconFont from "@/components/IconFont";
import { CommonModal } from "@/pages/OrderModule/common/components/CommonModal";
import Typography from "@/pages/OrderModule/common/components/Typography";
import { Alert, Button, Col, Form, Modal, Row, Select, Space, Tooltip, message } from "antd";
import OrderStatusLabelValue from "./OrderStatusLabelValue";
import CommonLoading from "@/components/CommonLoading";
import { queryExpressList, updateLogisticsOp, updateExpressCompany, getWaybillByOutboundNo } from "../../service";
import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { find } from "lodash";

const { Option } = Select;

//找，用，倉的渲染
const renderChannelIcon = flag => {
	if (flag == 1) {
		return (
			<span
				style={{
					display: "inline-block",
					width: "20px",
					height: "20px",
					lineHeight: "20px",
					borderRadius: "50%",
					backgroundImage: "linear-gradient(45deg, #0071F0, #5AA9FF)",
					color: "#fff",
					textAlign: "center",
					fontSize: "12px"
				}}
			>
				找
			</span>
		);
	} else if (flag == 2) {
		return (
			<span
				style={{
					display: "inline-block",
					width: "20px",
					height: "20px",
					lineHeight: "20px",
					borderRadius: "50%",
					backgroundImage: "linear-gradient(45deg, #981FDD, #CE6FFF)",
					color: "#fff",
					textAlign: "center",
					fontSize: "12px"
				}}
			>
				仓
			</span>
		);
	} else if (flag == 3) {
		return (
			<span
				style={{
					display: "inline-block",
					width: "20px",
					height: "20px",
					lineHeight: "20px",
					borderRadius: "50%",
					backgroundImage: "linear-gradient(45deg, #FF9000, #FFD285)",
					color: "#fff",
					textAlign: "center",
					fontSize: "12px"
				}}
			>
				用
			</span>
		);
	}
};

function renderStatusValue(val, props = {}) {
	return <Typography {...props}>{val}</Typography>;
}

/** 批量修改快递 */
function SetExpressModal(props) {
	const { onCancel, handleOk, data, setData } = props;

	const [form] = Form.useForm();

	const [loading, setLoading] = useState(false);
	//下拉快递列表
	const [expressList, setExpressList] = useState([]);

	const [note, setNote] = useState(""); //当前选中的快递说明
	// 定时器
	const [timer, setTimer] = useState();
	// 轮询请求超过60次关闭
	const [timerNum, setTimerNum] = useState(0);
	const navigate = useNavigate();
	useEffect(() => {
		getExpressList();
		form.resetFields();
	}, []);

	//获取快递列表
	const getExpressList = async () => {
		// 针对京东的订单，订单标签有“送货上门”的数据，这里操作修改快递的时候需要做特殊的判断，送货上门的快递只能修改支持送货上门的快递，不支持修改为普通的快递，弹窗选择快递的数据要把普通的数据清除掉
		const list = data?.order?.orderLabelArray;
		let flag = false;
		if (Array.isArray(list)) {
			flag = list.some(item => item.labelName === "送货上门");
		}
		setLoading(true);
		const res = await queryExpressList({
			// 可用快递列表 0:自发可用，1:全部可用
			type: 1,
			// 是否送货上门 0：否，1：是，可以为空，默认不是
			isUpDoor: flag ? 1 : 0
		});
		if (res.success) {
			setExpressList(res.data);
		} else {
			expressList?.length && setExpressList([]);
		}
		setLoading(false);
	};

	//修改快递
	const updateLogistics = async val => {
		setLoading(true);
		const expressCompany = expressList.find(item => item.baseExpressId === val?.expressId)?.baseExpressName;
		const { order } = data;
		const { success } = await updateExpressCompany({
			outboundNo: order.outboundNo,
			expressCompany: expressCompany,
			expressCompanyId: val?.expressId
		});
		if (success) {
			message.success("单据获取中");
			// 轮询调用接口获取物流单号
			setData({
				...data,
				order: {
					...data.order,
					expressCompany: expressCompany,
					waybillNo: "获取中..."
				}
			});
			getLogisticsNo(order.outboundNo, expressCompany);
			onCancel();
		}
		setLoading(false);
	};

	// 获取物流单号
	async function getLogisticsNo(outboundNo, expressCompany) {
		const res = await getWaybillByOutboundNo({ outboundNo });
		if (res.success && JSON.stringify(res.data) !== "{}") {
			setData({
				...data,
				order: {
					...data.order,
					expressCompany: expressCompany,
					waybillNo: res.data
				}
			});
		} else {
			// 重复请求60次以后不再请求
			if (timerNum >= 60) {
				setTimerNum(0);
				return;
			}
			const TIMERS = setTimeout(() => {
				const num = timerNum + 1;

				setTimerNum(num);
				getLogisticsNo(outboundNo, expressCompany);
			}, 1000);
			setTimer(TIMERS);
		}
	}

	//点击提交
	const onOk = () => {
		if (loading) {
			return false;
		}
		form
			.validateFields()
			.then(val => {
				updateLogistics(val);
			})
			.catch(err => {});
	};

	//下拉的选择
	const handleItemChange = e => {
		const item = find(expressList, ["baseExpressId", e]);
		setNote(item?.note);
		form.setFieldValue({
			expressId: e
		});
	};

	//快递下拉
	const expressListOption =
		expressList.length &&
		expressList.map(function (item) {
			return (
				<Option value={item.baseExpressId} key={item.id}>
					<Tooltip title={item.baseExpressName}>
						<span>{item.baseExpressName}</span>
						{renderChannelIcon(item.expressFlag)}
					</Tooltip>
				</Option>
			);
		});

	useEffect(() => {
		return () => {
			if (timer) clearTimeout(timer);
		};
	}, []);
	return (
		<CommonModal title={{ title: "批量修改快递" }} open={true} width="550px" onOk={onOk} onCancel={onCancel}>
			<Form form={form}>
				<Row>
					<Col flex="auto">
						<Form.Item name="expressId" rules={[{ required: true, message: "请选择快递" }]}>
							<Select
								placeholder={
									<>
										<Typography type="error">*</Typography>请选择修改快递
									</>
								}
								onChange={handleItemChange}
							>
								{expressListOption}
							</Select>
						</Form.Item>
					</Col>
					<Col>
						<Button
							onClick={() => {
								// navigate("/views/order/rule", { state: { tab1: '0', tab2: "4" } });
								navigate("/views/order/rule?tab1=0&tab2=4");
								onCancel();
							}}
							type="link"
						>
							<Typography color="#0068FF">
								<IconFont type="iconsetting02" />
							</Typography>
							&nbsp;&nbsp;<Typography color="#333">获取运单号设置</Typography>
						</Button>
					</Col>
				</Row>
				{note ? (
					<div style={{ width: 350 }}>
						<Typography color="#999">快递说明（{APP_TITLE}代发仓）：{note}</Typography>
					</div>
				) : (
					""
				)}
			</Form>
			<CommonLoading loading={loading} />
		</CommonModal>
	);
}

export default SetExpressModal;
